<template>
    <div>
        <div :class="{ fullscreen: fullscreen }" class="tinymce-container" :style="{ width: containerWidth }">
            <textarea :id="tinymceId" class="tinymce-textarea" />
            <!-- <div class="editor-custom-btn-container">
            <editorImage color="#1890ff" class="editor-upload-btn  " :class="myFixed ? 'myFixed' : ''" @successCBK="imageSuccessCBK" />
        </div> -->
        </div>
        <van-popup v-model="showCustomUpImage">
            <div class="customImg">
                <h3>上传图片</h3>
                <van-uploader :max-count="1" :after-read="customImgAfterRead" :max-size="8 * 1024 * 1024" @oversize="onOversize"></van-uploader>
            </div>
        </van-popup>
    </div>
</template>
<script>
/**
 * docs:
 * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
 */
import editorImage from "./components/EditorImage";
import plugins from "./plugins";
import toolbar from "./toolbar";
import load from "./dynamicLoadScript";
// import zh_CN from "./zh_CN.js";

// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
// const tinymceCDN = "https://cdn.tiny.cloud/1/no-api-key/tinymce/6/tinymce.min.js";
const tinymceCDN = "https://lib.baomitu.com/tinymce/5.6.2/tinymce.min.js";
// const tinymceCDN = "./tinymce.js";
import { uploadImg } from "@/https/api";
import { Toast } from "vant";
export default {
    name: "Tinymce",
    components: { editorImage },
    props: {
        id: {
            type: String,
            default: function () {
                return "vue-tinymce-" + +new Date() + ((Math.random() * 1000).toFixed(0) + "");
            },
        },
        value: {
            type: String,
            default: "",
        },
        toolbar: {
            type: Array,
            required: false,
            default() {
                return [];
            },
        },
        menubar: {
            type: String,
            default: "file edit insert view format table",
        },
        height: {
            type: [Number, String],
            required: false,
            default: 400,
        },
        width: {
            type: [Number, String],
            required: false,
            default: "auto",
        },
        draftType: {
            type: [Number, String],
            default() {
                return 1;
            },
        },
    },
    data() {
        return {
            showCustomUpImage: false,
            hasChange: false,
            hasInit: false,
            tinymceId: this.id,
            fullscreen: false,
            languageTypeList: {
                en: "en",
                zh: "zh_CN",
                es: "es_MX",
                ja: "ja",
            },
            myFixed: false,
            myEditor: null,
        };
    },
    computed: {
        containerWidth() {
            const width = this.width;
            if (/^[\d]+(\.[\d]+)?$/.test(width)) {
                // matches `100`, `'100'`
                return `${width}px`;
            }
            return width;
        },
    },
    watch: {
        value(val) {
            if (!this.hasChange && this.hasInit) {
                this.$nextTick(() => window.tinymce.get(this.tinymceId).setContent(val || ""));
            }
        },
    },
    mounted() {
        this.init();
        window.addEventListener("scroll", this.handleScroll); // 监听页面滚动
    },
    activated() {
        if (window.tinymce) {
            this.initTinymce();
        }
    },
    deactivated() {
        this.destroyTinymce();
    },
    destroyed() {
        this.destroyTinymce();
    },
    methods: {
        onOversize() {
            Toast("封面图大小不能超过 8MB");
        },
        async customImgAfterRead(file) {
            this.showCustomUpImage = false;
            Toast.loading({
                duration: 0,
                forbidClick: true,
                message: "图片上传中...",
            });
            let formData = new FormData();
            formData.append("file", file.file);
            let res = await uploadImg(formData);
            Toast.clear();
            if (res.code === 1) {
                Toast("上传成功");
                this.myEditor.insertContent(`<img src="${res.data.url}">`);
            } else {
                Toast("上传失败");
            }
        },
        // 获取页面滚动距离
        handleScroll() {
            let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
            // console.log(scrollTop, '滚动距离')
            if (scrollTop >= 200) {
                this.myFixed = true;
            } else {
                this.myFixed = false;
            }
        },
        init() {
            // dynamic load tinymce from cdn
            load(tinymceCDN, (err) => {
                if (err) {
                    this.$message.error(err.message);
                    return;
                }
                this.initTinymce();
            });
        },
        initTinymce() {
            const _this = this;
            // window.tinymce.addI18n("zh_CN", zh_CN);
            window.tinymce.init({
                selector: `#${this.tinymceId}`,
                branding: false,
                language: "zh_CN",
                height: this.height,
                min_height: this.height,
                body_class: "panel-body ",
                object_resizing: false,
                toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
                toolbar_mode: "floating",
                menubar: this.menubar,
                plugins: plugins,
                end_container_on_empty_block: true,
                powerpaste_word_import: "clean",
                advlist_bullet_styles: "square",
                font_formats:
                    "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';等线='等线';方正姚体='方正姚体';方正舒体='方正舒体';华文仿宋='华文仿宋';华文楷体='华文楷体';华文隶属='华文隶属';华文细黑='华文细黑';微软雅黑='微软雅黑';新宋体='新宋体';华文行楷='华文行楷';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
                fontsize_formats: "12px 14px 16px 18px 20px 22px 24px 26px 28px 30px 32px 34px 36px",
                advlist_number_styles: "default",
                imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"],
                default_link_target: "_blank",
                link_title: false,
                toolbar_sticky: true,
                nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
                image_dimensions: false,
                image_advtab: false,
                automatic_uploads: false,
                content_style: "html{min-height:400px!important}img{max-width:98%;height:auto;}body{min-height:400px!important}",
                mobile: {
                    plugins: plugins,
                    // toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
                    toolbar: `undo redo ${
                        this.draftType == 2 ? "customImage" : ""
                    } bold italic underline strikethrough alignleft | aligncenter alignright  alignjustify formatselect fontselect fontsizeselect fontfamily fontsize blocks outdent indent numlist bullist forecolor backcolor removeformat pagebreak charmap emoticons fullscreen insertfile preview`,
                    toolbar_mode: "sliding",
                    height: this.height,
                    automatic_uploads: false,
                    min_height: this.height,
                    images_upload_handler: async (value, success, err) => {
                        let formData = new FormData();
                        const fileOfBlob = value.blob();
                        formData.append("file", fileOfBlob);
                        let res = await uploadImg(formData);
                        if (res.code === 1) {
                            success(res.data.url);
                        } else {
                            err();
                        }
                    },
                },
                init_instance_callback: (editor) => {
                    if (this.value) {
                        editor.setContent(this.value);
                    }
                    this.hasInit = true;
                    editor.on("NodeChange Change KeyUp SetContent", () => {
                        this.hasChange = true;
                        this.$emit("input", editor.getContent());
                    });
                },
                setup(editor) {
                    _this.myEditor = editor;
                    editor.on("FullscreenStateChanged", (e) => {
                        _this.fullscreen = e.state;
                    });
                    //定义一个名为 customImage 的toolbar
                    editor.ui.registry.addButton("customImage", {
                        text: `<svg width="24" height="24"><path d="M5 15.7l3.3-3.2c.3-.3.7-.3 1 0L12 15l4.1-4c.3-.4.8-.4 1 0l2 1.9V5H5v10.7zM5 18V19h3l2.8-2.9-2-2L5 17.9zm14-3l-2.5-2.4-6.4 6.5H19v-4zM4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 01-1-1V4c0-.6.4-1 1-1zm6 8a2 2 0 100-4 2 2 0 000 4z" fill-rule="nonzero"></path></svg>`,
                        tooltip: "上传图片",
                        onAction: () => {
                            _this.showCustomUpImage = true;
                        },
                    });
                },
            });
        },
        destroyTinymce() {
            const tinymce = window.tinymce.get(this.tinymceId);
            if (this.fullscreen) {
                tinymce.execCommand("mceFullScreen");
            }

            if (tinymce) {
                tinymce.destroy();
            }
        },
        setContent(value) {
            console.log(value);
            window.tinymce.get(this.tinymceId).setContent(value);
        },
        getContent() {
            window.tinymce.get(this.tinymceId).getContent();
        },
        imageSuccessCBK(arr) {
            const _this = this;
            arr.forEach((v) => {
                window.tinymce.get(_this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" >`);
            });
        },
    },
};
</script>

<style scoped>
.customImg {
    width: 4.6rem;
    padding: 0.3rem;
    box-sizing: border-box;
    text-align: center;
}
.customImg h3 {
    margin-bottom: 0.3rem;
}
.tinymce-container {
    position: relative;
    line-height: normal;
}
.tinymce-container >>> .mce-fullscreen {
    z-index: 10000;
}
.tinymce-textarea {
    visibility: hidden;
    z-index: -1;
}
.editor-custom-btn-container {
    position: absolute;
    right: 4px;
    top: 4px;
    z-index: 2005;
}
.fullscreen .editor-custom-btn-container {
    z-index: 10000;
    position: fixed;
}
.editor-upload-btn {
    display: inline-block;
}
.myFixed {
    position: fixed;
    top: 5px;
    right: 45px;
}
.panel-body {
    height: 100%;
}
</style>
